<?php

class Sredis
{
    static $interface;
    public $handle;

    static function getInterface()
    {
        if (is_null(self::$interface)) self::$interface = new self();
        return self::$interface;
    }

    function __construct()
    {
        //Logger::getInterface()->error('REGIDS CONNECTION begin');
        $this->handle = false;
        try {
            $config = new Yaf_Config_Ini(APPLICATION_PATH . '/conf/application.ini');
            $redis = new Predis\Client(array(
                    'scheme' => 'tcp',
                    'host' => $config->product->redis->host,
                    'port' => $config->product->redis->port,
                )
            );
            if ($config->product->redis->passwd) $redis->auth($config->product->redis->passwd);
            if ($redis->getConnection()) {
                $this->handle = $redis;
            } else {
                Logger::getInterface()->error('REGIDS CONNECTION FAIL');
            }
        } catch (Exception $e) {
            Logger::getInterface()->error('REGIDS CONNECTION FAIL' . json_encode($e->getMessage()));
        }
    }

    private static $connections = array(); //定义一个对象池
    private static $servers = array(); //定义redis配置文件

    /**
     * $conf = array(
     *      'RA' => array('127.0.0.1',6379)   //定义Redis配置
     * );
     * RedisPool::addServer($conf); //添加Redis配置
     * $redis = RedisPool::getRedis('RA'); //连接RA，使用默认0库
     *
     * @param $conf
     */
    public static function addServer($conf) //定义添加redis配置方法
    {
        foreach ($conf as $alias => $data) {
            self::$servers[$alias] = $data;
        }
    }

    public static function getRedis($alias = 'default', $select = 0)//两个参数要连接的服务器KEY,要选择的库
    {

        Logger::getInterface('redis')->error(json_encode(self::$connections));
        if (!array_key_exists($alias, self::$connections)) {  //判断连接池中是否存在
            $redis = new Predis\Client(array(
                    'scheme' => 'tcp',
                    'host' => self::$servers[$alias][0],
                    'port' => self::$servers[$alias][1],
                )
            );
            Logger::getInterface('redis')->error('new redis connect');
            self::$connections[$alias] = $redis;
            if (isset(self::$servers[$alias][2]) && self::$servers[$alias][2] != "") {
                self::$connections[$alias]->auth(self::$servers[$alias][2]);
            }
        }
        self::$connections[$alias]->select($select);
        return self::$connections[$alias];
    }
}